﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class Get_Article_ListController : BaseController
    {
        public IArticleService _article { get; set; }
        public IArticle_categoryService _article_category { get; set; }
        [HttpGet]
        public IActionResult Get(int page=1,int page_size=20,int id=0,int channel_id=1,int shop_id=0)
        {
            var cate = _article_category.GetModel(id);
            if (cate == null&&id>0)
            {
                return Ok(new { status = 0, msg = "分类不存在！" });
            }
            List<Article_category> allcate = _article_category.GetList(1, 1000, "where id>0", "id asc");
            if (id > 0)
                allcate = allcate.Where(a => a.class_list.Contains("," + id + ",")).ToList();
            string class_list = "0,";
            foreach (var item in allcate)
            {
                class_list = class_list + item.id + ",";
            }

            page = page > 0 ? page : 1;
            string strwhere = "where status=0 and channel_id="+channel_id+ " and category_id in (" + Utils.DelLastComma(class_list) + ")";
            if(shop_id>0)
                strwhere = "where shop_id="+shop_id+" and status=0 and channel_id=" + channel_id + " and category_id in (" + Utils.DelLastComma(class_list) + ")";
            var list = _article.GetList(page, page_size, strwhere, "add_time desc,id desc");
            int totalcount = _article.RecordCount(strwhere);
            int pageCount = totalcount / page_size;
            if (pageCount < 1)
            {
                pageCount=1;
            }
            if (totalcount % page_size > 0)
            {
                pageCount += 1;
            }
            if (pageCount <= 1)
            {
                pageCount=1;
            }
            var sys = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            for (int i = 0; i < list.Count; i++)
            {
                list[i].img_url = sys.weburl + list[i].img_url;
            }
            return Ok(new { status = 1, list = list, page = page, page_count = pageCount, total_count = totalcount });
        }
    }
}